package com.jxwifi.cloud.quickclean;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Point;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.ViewDragHelper;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import com.jxwifi.cloud.quickclean.mycenter.FeedBackActivity;
import com.jxwifi.cloud.quickclean.utils.Density;
import com.jxwifi.cloud.quickclean.utils.IMGRigTopPointView;
import com.jxwifi.cloud.quickclean.utils.ToastUtilsKing;
import com.nineoldandroids.view.ViewHelper;
import com.umeng.analytics.MobclickAgent;
import com.youth.banner.Banner;

import com.bumptech.glide.Glide;
import com.idroid.widget.CircleImageView;
import com.idroid.widget.LoadDialog;
import com.jxwifi.cloud.quickclean.address.AddressListActivity;
import com.jxwifi.cloud.quickclean.app.AccountMgr;
import com.jxwifi.cloud.quickclean.app.ClientBasicActivity;
import com.jxwifi.cloud.quickclean.app.LocationGaoDe;
import com.jxwifi.cloud.quickclean.app.PasswordLogin;
import com.jxwifi.cloud.quickclean.app.StateUtils;
import com.jxwifi.cloud.quickclean.bean.HomeaddressBean;
import com.jxwifi.cloud.quickclean.login.BindPhoneActivity;
import com.jxwifi.cloud.quickclean.main.MainPresenter;
import com.jxwifi.cloud.quickclean.main.MainView;
import com.jxwifi.cloud.quickclean.upgrade.UpgradeNotice;
import com.jxwifi.cloud.quickclean.utils.ToastUtils;
import com.view.SuperSwipeRefreshLayout;

import java.lang.reflect.Field;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends ClientBasicActivity implements MainView {

    private String TAG = this.getClass().getSimpleName();
    @Bind(R.id.drawer_layout)
    DrawerLayout mDrawerLayout;
    @Bind(R.id.nav_view)
    NavigationView mNavView;
    @Bind(R.id.rel_main_head)
    RelativeLayout rel_main_head;

    @Bind(R.id.rel_main_null_address)
    RelativeLayout mRelMainNullAddress;//无地址时的布局
    @Bind(R.id.rel_main_address)
    RelativeLayout mRelMainAddress;//有地址数据时的布局
    @Bind(R.id.tv_main_address_text)
    TextView mTvMainAddressText;//地址第一行
    @Bind(R.id.tv_main_address_detailed)
    TextView mTvMainAddressDetails;//地址详情
    @Bind(R.id.tv_main_order_doing)
    TextView mTvMainOrderDoing;
    @Bind(R.id.sv_main_head)
    ScrollView mSvMainHead;

    @Bind(R.id.srl_my_order_list)
    SuperSwipeRefreshLayout mSrlMyOrderList;

    @Bind(R.id.rel_main_order_doing)
    RelativeLayout mRelMainOrderDoing;//进行中的订单布局

    //2019-10-16版本迭代，新UI设计
    @Bind(R.id.main_banner)
    Banner mMainBanner;
    @Bind(R.id.rv_main_list)
    RecyclerView mRvMainList;
    @Bind(R.id.rel_banner)
    RelativeLayout rel_banner;
    @Bind(R.id.img_dog)
    IMGRigTopPointView img_dog;

    private MainPresenter mPresenter;

    private HomeaddressBean mAddress;

    private int mDefaultPrice;//订金字段
    private int mHours;//小时
    private String mCostDescription;//费用描述

    private int mEstimateMoney = 0;  //预计的价格
    private long mClickFirstTime = 0;
    private LoadDialog mLoadDialog;//加载动画

    private boolean mIsAddress = true;//用于判断地址是否为空

    private String mProductPriceCode;
    private int loginCount = 0;
    private DisplayMetrics dm;
    private boolean unreadMessages = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        openEventBus();
        dm =  getResources().getDisplayMetrics();
        /*Display display = getWindowManager().getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);
        int width = size.x;
        int height = size.y;
        ViewGroup.LayoutParams params=rel_banner.getLayoutParams();
        params.height =(int)(225120 / dm.densityDpi);
        rel_banner.setLayoutParams(params);*/
        //Density.setDensity(getApplication(), this);

        WindowManager windowManager = (WindowManager) getApplication().getSystemService(Context.WINDOW_SERVICE);
        Display display = windowManager.getDefaultDisplay();
        Point outPoint = new Point();
        if (Build.VERSION.SDK_INT >= 19) {
            // 可能有虚拟按键的情况
            display.getRealSize(outPoint);
        } else {
            // 不可能有虚拟按键
            display.getSize(outPoint);
        }
        int mRealSizeWidth;//手机屏幕真实宽度
        int mRealSizeHeight;//手机屏幕真实高度
        mRealSizeHeight = outPoint.y;
        mRealSizeWidth = outPoint.x;


        DisplayMetrics dm = getApplicationContext().getResources().getDisplayMetrics();
        int screenWidth = dm.widthPixels;
        int screenHeight = dm.heightPixels;

        ViewGroup.LayoutParams params=rel_banner.getLayoutParams();
        Log.i(TAG, "onCreate ==> 广告图width = "+rel_banner.getLayoutParams().width/*+" 广告图height = "+params.height+" 屏幕width = "+width+" 屏幕height = "+height*/+" dpi = "+dm.densityDpi+" 密度 = "+dm.density);
        Log.i(TAG,"mRealSizeHeight = "+mRealSizeHeight+" mRealSizeWidth = "+mRealSizeWidth+" screenWidth = "+screenWidth+" screenHeight = "+screenHeight);
        params.height = (int)(mRealSizeWidth*dm.densityDpi/dm.density/317.0642075325);//参考小程序
        //params.height = (int)(206.4761904762 * dm.density);//参考小程序
        Log.i(TAG,"按像素比例3.52 height = "+(int)(mRealSizeWidth*dm.densityDpi/dm.density/317.0642075325)+" 按密度比例 height = "+(int)(206.4761904762 * dm.density));
        rel_banner.setLayoutParams(params);

        if (LocationGaoDe.getLatitude() == 0.0) {
            new LocationGaoDe().init(getApplicationContext());
            LocationGaoDe.startLocation();
        }
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                UpgradeNotice.UpgradeData(mBaseContext, TAG, 1, MainActivity.this);//升级通知
            }
        }, 500);
        mLoadDialog = new LoadDialog(mBaseContext, "");
        mPresenter = new MainPresenter(mBaseContext, this);
        mSvMainHead.setFillViewport(true);
        Glide.with(this).load(R.mipmap.dog).into(img_dog);

        setDrawerLeftEdgeSize(this, mDrawerLayout, 0.3f);
        /*//在划出边栏时添加动画特效
        mDrawerLayout.setDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {
                Log.d("HK", "onDrawerSlide slideOffset=" + slideOffset);
                View mContent = mDrawerLayout.getChildAt(0);
                View mRightContent = mDrawerLayout.getChildAt(2);
                float scale = 1 - slideOffset;
                float rightScale = 0.8f + scale * 0.2f;
                if (drawerView.getTag().equals("LEFT")) {
                    float leftScale = 1 - 0.3f * scale;

                    ViewHelper.setScaleX(mNavView, leftScale);
                    ViewHelper.setScaleY(mNavView, leftScale);
                    ViewHelper.setAlpha(mNavView, 0.6f + 0.4f * (1 - scale));

                    ViewHelper.setTranslationX(mContent,
                            mNavView.getMeasuredWidth() * (1 - scale));
                    ViewHelper.setPivotX(mContent, 0);
                    ViewHelper.setPivotY(mContent,
                            mContent.getMeasuredHeight() / 2);
                    mContent.invalidate();
                    ViewHelper.setScaleX(mContent, rightScale);
                    ViewHelper.setScaleY(mContent, rightScale);
                } else if (drawerView.getTag().equals("RIGHT")) {
                    float rScale = 1 - 0.3f * scale;
                    ViewHelper.setScaleX(mRightContent, rScale);
                    ViewHelper.setScaleY(mRightContent, rScale);
                    ViewHelper.setAlpha(mRightContent, 0.6f + 0.4f * (1 - scale));

                    ViewHelper.setTranslationX(mContent,
                            -mNavView.getMeasuredWidth() * slideOffset);
                    ViewHelper.setPivotX(mContent, mRightContent.getMeasuredWidth());
                    ViewHelper.setPivotY(mContent,
                            mContent.getMeasuredHeight() / 2);
                    mContent.invalidate();
                    ViewHelper.setScaleX(mContent, rightScale);
                    ViewHelper.setScaleY(mContent, rightScale);
                }
            }


            @Override
            public void onDrawerOpened(View drawerView) {

            }

            @Override
            public void onDrawerClosed(View drawerView) {

            }

            @Override
            public void onDrawerStateChanged(int newState) {

            }

        });*/

    }

    public void initView() {
        //mPresenter.fgView();
        mPresenter.Sideslip();
        mPresenter.initAdvert();
        //mPresenter.function();
        mPresenter.navigation(dm);
    }

    @OnClick({R.id.img_main_personal_center, R.id.rel_main_order_doing, R.id.rel_main_address
            , R.id.rel_main_null_address, R.id.img_service, R.id.img_dog})
    void clickCK(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {

            //反馈建议
            case R.id.img_dog:

                    intent.setClass(mBaseContext, FeedBackActivity.class);
                    intent.putExtra("unreadMessages",unreadMessages);
                    startActivity(intent);

                MobclickAgent.onEvent(this, "main_feedback_center");
                break;
            //个人消息
            case R.id.img_main_personal_center:
                if (!TextUtils.isEmpty(AccountMgr.gettell(mBaseContext))) {
                    mDrawerLayout.openDrawer(GravityCompat.START);
                } else {
                    intent.setClass(mBaseContext, BindPhoneActivity.class);
                    startActivity(intent);
                }
                MobclickAgent.onEvent(this, "main_personal_center");
                break;
            //进行中的订单
            case R.id.rel_main_order_doing:
                if (!TextUtils.isEmpty(AccountMgr.gettell(mBaseContext))) {
                    mPresenter.OngoingOrders();
                } else {
                    intent.setClass(mBaseContext, BindPhoneActivity.class);
                    startActivity(intent);
                }
                MobclickAgent.onEvent(this, "main_order_doing");
                break;
            //有地址布局点击操作
            case R.id.rel_main_address:
                if (!TextUtils.isEmpty(AccountMgr.gettell(mBaseContext))) {
                    intent.setClass(mBaseContext, AddressListActivity.class);
                    startActivity(intent);
                } else {
                    intent.setClass(mBaseContext, BindPhoneActivity.class);
                    startActivity(intent);
                }
                MobclickAgent.onEvent(this, "main_address");
                break;
            //地址无数据布局点击操作
            case R.id.rel_main_null_address:
                if (!TextUtils.isEmpty(AccountMgr.gettell(mBaseContext))) {
                    intent.setClass(mBaseContext, AddressListActivity.class);
                    startActivity(intent);
                } else {
                    intent.setClass(mBaseContext, BindPhoneActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.img_service:
                mPresenter.CustomerService();
                MobclickAgent.onEvent(this, "main_customer_service");
                break;
        }
    }

    @Override
    public RecyclerView getRecyclerView() {
        return mRvMainList;
    }

    @Override
    public Banner getBanner() {
        return mMainBanner;
    }

    @Override
    public SuperSwipeRefreshLayout getSwip() {
        return mSrlMyOrderList;
    }

    @Override
    public void onProductPriceCode(String productPriceCode) {
        mProductPriceCode = productPriceCode;
    }

    @Override
    public TextView getOrderDoingText() {
        return mTvMainOrderDoing;
    }

    @Override
    public void onAfterDo() {
        initView();
    }

    @Override
    public NavigationView getNav() {
        return mNavView;
    }

    @Override
    public DrawerLayout getDrawer() {
        return mDrawerLayout;
    }


    @Override
    public FragmentManager getFrgaments() {
        return getSupportFragmentManager();
    }

    @Override
    public CircleImageView getImgHead() {
        return mNavView.getHeaderView(0).findViewById(R.id.img_personal_data_photo);
    }

    @Override
    public LinearLayout getGradeDescription() {
        return mNavView.getHeaderView(0).findViewById(R.id.lin_grade_dis);
    }

    @Override
    public ImageView getImgGradeDescription() {
        return mNavView.getHeaderView(0).findViewById(R.id.img_grade_descripton);
    }

    @Override
    public TextView getName() {
        return mNavView.getHeaderView(0).findViewById(R.id.name_tv);
    }

    @Override
    public TextView getGradeName() {
        return mNavView.getHeaderView(0).findViewById(R.id.tv_grade_name);
    }

    @Override
    public void getDefaultPrice(int defaultprice) {
        mDefaultPrice = defaultprice;
    }

    @Override
    public void onHours(int hours) {
        mHours = hours;
    }

    @Override
    public void onCostDescription(String description) {
        mCostDescription = description;
    }

    @Override
    public WindowManager getManager() {
        return getWindowManager();
    }

    @Override
    public RelativeLayout getOrderDoing() {
        return mRelMainOrderDoing;
    }



    @Override
    public int getEstimateMoney() {
        return mEstimateMoney;
    }

    @Override
    public void onFailure(int errorCode, String msg) {
        Toast toast = Toast.makeText(mBaseContext, msg, Toast.LENGTH_SHORT);
        ToastUtils.showMyToast(toast, 3000);
    }

    @Override
    public void onAddressBean(HomeaddressBean address) {
        //判断地址信息是否未空，为空显示空布局
        if (address != null) {
            mIsAddress = true;
            mRelMainAddress.setVisibility(View.VISIBLE);
            mRelMainNullAddress.setVisibility(View.GONE);
            mTvMainAddressText.setText(address.getProvince() + " " + address.getCity() + " " + address.getArea());
            StateUtils.typeAddress(mBaseContext, mTvMainAddressText, address.getTypeCode());
            mTvMainAddressDetails.setText(address.getAddress());
            StateUtils.AddLat = address.getLat();
            StateUtils.AddLon= address.getLon();
        } else {
            mIsAddress = false;
            mRelMainNullAddress.setVisibility(View.VISIBLE);
            mRelMainAddress.setVisibility(View.GONE);
        }
    }

    @Override
    public void oninfo() {
        PasswordLogin.passwordlogin(mBaseContext, TAG, AccountMgr.gettell(mBaseContext), AccountMgr.getpassword(mBaseContext));
        if (PasswordLogin.mIsLogin) {
            mPresenter.getinfo();
        }else{
            //出现402时，再请求一次
            Log.i(TAG,"oninfo ==> loginCount = "+loginCount);
            if(loginCount == 0){
                loginCount++;
                Log.i(TAG,"PasswordLogin.passwordlogin ++");
                PasswordLogin.passwordlogin(mBaseContext, TAG, AccountMgr.gettell(mBaseContext), AccountMgr.getpassword(mBaseContext));
            }
        }
    }

    @Override
    public void ondata() {
        PasswordLogin.passwordlogin(mBaseContext, TAG, AccountMgr.gettell(mBaseContext), AccountMgr.getpassword(mBaseContext));
        if (PasswordLogin.mIsLogin) {
            mPresenter.getdata();
        }
    }

    @Override
    public void onAsynData() {
        PasswordLogin.passwordlogin(mBaseContext, TAG, AccountMgr.gettell(mBaseContext), AccountMgr.getpassword(mBaseContext));
        if (PasswordLogin.mIsLogin) {
            mPresenter.getAsynData();
        }
    }

    @Override
    public void onPlaceOrder(int postions) {
        PasswordLogin.passwordlogin(mBaseContext, TAG, AccountMgr.gettell(mBaseContext), AccountMgr.getpassword(mBaseContext));
        if (PasswordLogin.mIsLogin) {
            mPresenter.PlaceOrder(postions);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mLoadDialog.show();
        mPresenter.getinfo();
        //mPresenter.getAsynData();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mLoadDialog.dismiss();
            }
        }, 1000);
    }

    @Override
    public void onBackPressed() {
        long secondTime = System.currentTimeMillis();
        if (secondTime - mClickFirstTime > 2000) {
            Toast.makeText(mBaseContext, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            mClickFirstTime = secondTime;
            return;
        } else {
            Glide.get(mBaseContext).clearMemory();
            LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(new Intent(EXITAPP));
            System.gc();
        }
        super.onBackPressed();
    }

    @Override
    public void setMessageNum(int num) {
        Log.i(TAG,"setMessageNum ==> num = "+num);
        if (num != 0){
            unreadMessages = true;
            img_dog.setMessageNum(num);
            //img_dog.setPoint(imgPoint.getWidth()-imgPoint.getPaddingRight(),imgPoint.getPaddingTop());
            img_dog.setPointMode(IMGRigTopPointView.NUMBER_POINT);
            img_dog.setHaveMesage(true);
        }else{
            unreadMessages = false;
            img_dog.setPointMode(IMGRigTopPointView.NO_POINT);
        }

    }

    @Override
    public void showGradeDescription() {
        //Log.i(TAG,"等级说明");
        //ToastUtilsKing.show(this,"等级说明： 根据您的消费、活跃度，我们会定期评估您的等级，等级越高，便利越多，福利越多。",3000);
        ToastUtilsKing.middleShow(this,"等级说明： 根据您的消费、活跃度，我们会定期评估您的等级，等级越高，便利越多，福利越多。");
    }

    /**
     * 设置DrawerLayout全屏滑动，参数为1的时候
     * @param activity               当前activity
     * @param drawerLayout           抽屉
     * @param displayWidthPercentage 滑动弹出侧滑栏的范围，0-1
     */
    private void setDrawerLeftEdgeSize(Activity activity, DrawerLayout drawerLayout,float displayWidthPercentage) {

        if (activity == null || drawerLayout == null) return;
        try {
            // 找到 ViewDragHelper 并设置 Accessible 为true
            Field leftDraggerField = drawerLayout.getClass().getDeclaredField("mLeftDragger");//Right
            leftDraggerField.setAccessible(true);
            ViewDragHelper leftDragger = (ViewDragHelper) leftDraggerField.get(drawerLayout);
            // 找到 edgeSizeField 并设置 Accessible 为true
            Field edgeSizeField = leftDragger.getClass().getDeclaredField("mEdgeSize");
            edgeSizeField.setAccessible(true);
            int edgeSize = edgeSizeField.getInt(leftDragger);
            // 设置新的边缘大小方法1
            Point displaySize = new Point();
            activity.getWindowManager().getDefaultDisplay().getSize(displaySize);
            edgeSizeField.setInt(leftDragger, Math.max(edgeSize, (int) (displaySize.x *
                    displayWidthPercentage)));

            // 设置新的边缘大小方法2
            /*DisplayMetrics dm = new DisplayMetrics();
            activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
            edgeSizeField.setInt(leftDragger, Math.max(edgeSize,
                    (int) (dm.widthPixels * displayWidthPercentage)));*/

            //获取 Layout 的 ViewDragCallBack 实例“mLeftCallback”
            //更改其属性 mPeekRunnable,取消页面长按效果
            Field leftCallbackField = drawerLayout.getClass().getDeclaredField("mLeftCallback");
            leftCallbackField.setAccessible(true);
            //因为无法直接访问私有内部类，所以该私有内部类实现的接口非常重要，通过多态的方式获取实例
            ViewDragHelper.Callback leftCallback = (ViewDragHelper.Callback) leftCallbackField.get(drawerLayout);
            Field peekRunnableField = leftCallback.getClass().getDeclaredField("mPeekRunnable");
            peekRunnableField.setAccessible(true);
            peekRunnableField.set(leftCallback, new Runnable() {
                @Override
                public void run() {

                }
            });
        } catch (NoSuchFieldException ignored) {

        } catch (IllegalArgumentException ignored) {

        } catch (IllegalAccessException ignored) {

        }

    }
}
